package com.example.springboot.utils;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;

public class WordToPdf {
	@Value("${FilePathForMac}")
	private String outputPathForMac;

	@Value("${WordToHtmlPATH}")
	private String outputPathForWindows;

	private final static Logger log = LoggerFactory.getLogger(WordToPdf.class);

	@Test
	public void test() throws Exception{
		//windows
		docPdf("D:\\workspace\\race-rent\\src\\main\\resources\\wordToHtml\\赛事服务合同模板文件.docx",
                "D:\\workspace\\race-rent\\src\\main\\resources\\wordToHtml\\赛事服务合同模板文件.pdf");
		//mac
//		docPdf("/Users/cpf/workspace/race-rent/src/main/resources/wordToHtml/赛事服务合同模板文件.docx",
//				"/Users/cpf/workspace/race-rent/src/main/resources/wordToHtml/赛事服务合同模板文件.pdf");
	}

	public  String docPdf(String inPath, String outPath) throws Exception{
		if (!isWordLicense()) {
			return null;
		}
		try {
			File file = null;
			file = new File(outPath);// 新建一个空白pdf文档
			FileOutputStream os = new FileOutputStream(file);
			Document doc = new Document(inPath); // Address是将要被转化的word文档
			doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
		} catch (Exception e) {
			e.printStackTrace();
		}
		// EPUB, XPS, SWF 相互转换
		return outPath;
	}

	/**
	 * @Description: 验证aspose.word组件是否授权：无授权的文件有水印和试用标记
	 */
	public  boolean isWordLicense() {
		InputStream is = ExcelToPdf.class.getClassLoader().getResourceAsStream("license.xml");
		boolean result = false;
		License excelLicense = new License();
		try {
			excelLicense.setLicense(is);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// outputStream转inputStream
	public  ByteArrayInputStream parse(OutputStream out) throws Exception {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		baos = (ByteArrayOutputStream) out;
		ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		return swapStream;
	}

}
